<?php

namespace app\adminapi\controller\v1\excel;

use app\adminapi\controller\AuthController;
use app\exceptions\AdminException;
use app\services\excel\ExcelOutEnterService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\App;
use think\facade\Filesystem;

class ExcelOutEnter extends AuthController
{


    public function __construct(App $app, ExcelOutEnterService $service)
    {
        parent::__construct($app);
        $this->services = $service;
    }


    /**
     * excel 导入基础方法
     * @return mixed
     */
    public function excelEnter()
    {
        //设置跨域请求
        header('Access-Control-Allow-Origin: *');
        header("Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,accessToken,website");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
        $file = $this->request->file('file');
        validate(
            [
                'file' => [
                    'fileExt' => 'xlsx,xls'
                ]
            ],
            [
                'file.fileExt' => '不支持的文件后缀',
            ]
        )->check(['file' => $file]);

        return app()->make('json')->successful($this->services->excelEnter($file));

    }

    /**
     * 导入学生数据
     * @return mixed
     */
    public function excelEnterStudent(){
        $where = $this->request->getMore([
            ['website_id',$this  -> website],
        ]);
        if (!$where['website_id']) throw new AdminException('缺少站点id');
        $filename =   $this ->excleComm();
        return app()->make('json')->successful($this->services->excelEnterStudent($filename,$where['website_id']));

    }

    /**
     * 导入题库
     * @return mixed
     */
    public function excelEnterQuestion(){
        $where = $this->request->getMore([
            ['website_id',$this  -> website],
        ]);
        if (!$where['website_id']) throw new AdminException('缺少站点id');
        $filename =   $this ->excleComm();
        return app()->make('json')->successful($this->services->excelEnterQuestion($filename,$where['website_id']));
    }

    /**
     * 导入公共方法
     * @return bool|string
     */
    public function excleComm(){
        //设置跨域请求

        $file = $this->request->file('file');
        if (!$file)   throw new AdminException('请选择需要上传的文件！');
        validate(
            [
                'file' => [
                    'fileExt' => 'xlsx,xls'
                ]
            ],
            [
                'file.fileExt' => '不支持的文件后缀',
            ]
        )->check(['file' => $file]);

        $filename = Filesystem::disk('public')->putFile('excel', $file);
        if (!$filename)   throw new AdminException('文件上传失败！');
        return $filename;
    }


    /**
     * excel学生基础信息导出
     */
    function excelStudentExport()
    {
        //设置跨域请求
        header('Access-Control-Allow-Origin: *');
        header("Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,accessToken,website");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
        $data = [
            ['title1' => '111', 'title2' => '222'],
            ['title1' => '111', 'title2' => '222'],
            ['title1' => '111', 'title2' => '222']
        ];
        $title = ['id', '专业名称','学生头像','学生姓名','性别','常住地址','邮政编码','身份证号','手机号','准考证号','入学批次','入学类型','学号','生日','政治面貌','毕业学校','学号'];
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //表头
        //设置单元格内容
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }
        $row = 2; // 从第二行开始
        foreach ($data as $item) {
            $column = 1;
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }

        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="学生信息表.xlsx"');//输出的文件名
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit();
//        return app()->make('json')->successful("成功");
    }


}